<?php
namespace App\Api\Controllers\Cqcbank;

use App\Api\Controllers\lianfuyouzheng\BaseController;
use Illuminate\Support\Facades\Log;
use App\Api\Controllers\Cqcbank\BaseController as base;
use phpseclib\Crypt\RSA;
use Rtgm\sm\RtSm2;

class PayController extends BaseController
{
    public function __construct()
    {

    }


    public function scan_pay($data, $config)
    {
        try {
            $params = [
                'ServiceType' => 'unified.trade.micropay',
                'Charset'=>'UTF-8',//可选值 UTF-8 ，默认为 UTF-8
                'MerchantNo' => $data['mch_id'],
                'TradeNo' => $data['out_trade_no'],
                'ProductDesc' => $data['desc'],
                'terminal_type' => '02',
                'terminal_id' => $data['terminal_id'],
                'TotalAmt' => bcmul($data['total_amount'], 100),
                'TerminalIp' => '127.0.0.1',
                'AuthCode' => $data['code'],
                'Str'    => uniqid(),
            ];

            //单品
            $isGoods = 2;
            if (isset($data['store_id']) && !empty($data['store_id'])) {
                $isGoods =  \App\Models\Store::where('store_id', $data['store_id'])->value('is_goods');
            }
            if (isset($data['goods_detail']) && !empty($data['goods_detail'])) {
                error_log(date('Y-m-d H:i:s')." 【重庆单品】： ".json_encode([$data['goods_detail'], $isGoods])."\n\n", 3, "/www/wwwlogs/wft/". 'prod-vbill'.date('Ymd').".log");
            }

            if (isset($data['goods_detail']) && !empty($data['goods_detail']) && $isGoods == 1) {
                $goods = json_decode($data['goods_detail'], true);
                $goodsArr = [];
                foreach ($goods['goods_detail'] as $v) {
                    $goodsArr[] = [
                        'quantity'  => $v['quantity'],
                        'goods_id'   => $v['goods_id'],
                        'price'     => $v['price'],
                        'goods_name' => $v['goods_name'],
                    ];
                }
                $params['CommodityMsg'] = base64_encode(json_encode([
                    'cost_price'   => $goods['cost_price'],
                    'receipt_id'   => (string)$goods['receipt_id'],
                    'goods_detail' => $goodsArr,
                ]));
            }

            $base = base::getInstance();
            $ret  = $base->params($params, $config)->build( 'OP3136530102000100011500');
            error_log(date('Y-m-d H:i:s')." 【重庆被扫】： ".json_encode([$params, $ret])."\n\n", 3, "/tmp/". 'cqc'.date('Ymd').".log");
//单品信息
//            "Detail" : "{"promotion_detail":[{"activity_id":"19087121","amount":90,"goods_detail":[{"discount_amount":90,"goods_id":"6910019002640","goods_remark":"","price":100,"quantity":1}],"merchant_contribute":90,"name":"测试","other_contribute":0,"promotion_id":"69093981632","scope":"SINGLE","type":"COUPON","wxpay_contribute":0}]}",


            if (isset($ret['payloadMap']) && !empty($ret['payloadMap'])) {
                //PayResult 0成功，非0失败
                if ($ret['payloadMap']['PayResult'] === "0") { //支付成功
                    if (isset($ret['payloadMap']['Detail']) && !empty($ret['payloadMap']['Detail'])) {
                        \App\Common\PaySuccessAction::addCoupon($data['out_trade_no'], $ret['payloadMap']['Detail'], 'pay');
                    }
                    return [
                        'status' => 1,
                        'message' => '支付成功',
                        'data' => $ret['payloadMap']
                    ];
                } else {
                    return [
                        'status' => 2,
                        'message' => $ret['payloadMap']['ErrMsg'],
                    ];
                }
            } else {
                return [
                    'status' => 3,
                    'message' => '支付异常',
                ];
            }
        } catch (\Exception $ex) {
            return [
                'status' => 3,
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine(),
            ];
        }
    }


    //查询订单 0-系统错误 1-成功 2-正在支付 3-失败 4.已经退款
    public function order_query($data, $config)
    {
        try {
            $params = [
                'ServiceType' => 'unified.trade.query',
                'Charset'=>'UTF-8',//可选值 UTF-8 ，默认为 UTF-8
                'MerchantNo' => $data['mch_id'],
                'terminal_id' => $data['terminal_id'],
                'TradeNo' => $data['out_trade_no'],
                'Str'    => uniqid(),
            ];

            $base = base::getInstance();
            $ret  = $base->params($params, $config)->build( 'OP3136530102000100011700');
            error_log(date('Y-m-d H:i:s')." 【重庆被扫查询】： ".json_encode([$params, $ret])."\n\n", 3, "/tmp/". 'cqc'.date('Ymd').".log");

            if (isset($ret['payloadMap']) && !empty($ret['payloadMap'])) {
                //PayResult 0成功，非0失败
                //"SUCCESS—支付成功
                //REFUND—转入退款
                //NOTPAY—未支付
                //CLOSED—已关闭
                //REVOKED/REVERSE—已撤销
                //USERPAYING—用户支付中
                //PAYERROR—支付失败(其他原因，如银行返回失败)"

                if ($ret['payloadMap']['TranStatus'] === "SUCCESS") { //支付成功
                    return [
                        'status' => 1,
                        'message' => '支付成功',
                        'data' => $ret['payloadMap']
                    ];
                } else if ($ret['payloadMap']['TranStatus'] === "USERPAYING") {
                    return [
                        'status' => 2,
                        'message' => '用户支付中',
                    ];
                } else {
                    return [
                        'status' => 3,
                        'message' => $ret['payloadMap']['TranDesc'],
                    ];
                }
            } else {
                return [
                    'status' => 3,
                    'message' => '支付异常',
                ];
            }
        } catch (\Exception $ex) {
            return [
                'status' => '0',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine(),
            ];
        }
    }


    //退款 0-系统错误 1-成功
    public function refund($data, $config)
    {
        try {
            $params = [
                'ServiceType' => 'unified.trade.refund',
                'Charset'=>'UTF-8',//可选值 UTF-8 ，默认为 UTF-8
                'MerchantNo' => $data['mch_id'],
                'TradeNo' => $data['out_trade_no'],
                'OutRefundNo' => $data['refund_no'],
                'TotalAmt' => $data['total_amount'] * 100,
                'RefundAmt' => $data['refund_amount'] * 100,
                'OperNo' => $data['mch_id'],
                'Str'    => uniqid(),
                'terminal_id' => $data['terminal_id'],
            ];

            $base = base::getInstance();
            $ret  = $base->params($params, $config)->build( 'OP3136530102000100011800');
            error_log(date('Y-m-d H:i:s')." 【重庆被扫退款】： ".json_encode([$params, $ret])."\n\n", 3, "/tmp/". 'cqc'.date('Ymd').".log");
//            var_dump($ret);
            if (isset($ret['payloadMap']['ResultCode']) && $ret['payloadMap']['ResultCode'] === "0") {
                return [
                    'status' => 1,
                    'message' => '退款成功',
                    'data' => [
                        'refund_count' => 1,
                        'out_trade_no'  => $ret['payloadMap']['TradeNo'],
                    ]
                ];
            } else {
                return [
                    'status' => 2,
                    'message' => $ret['payloadMap']['ErrorCode']
                ];
            }
        } catch (\Exception $ex) {
            return [
                'status' => 0,
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //退款查询 0-系统错误 1-成功 2-正在退款 3-失败
    public function refund_query($data)
    {
        try {


        } catch (\Exception $ex) {
            return [
                'status' => '0',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }





}
